package com.example.myapplication.rxjava;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;

import com.orhanobut.logger.Logger;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 类描述:
 * 创建人:   tangchao$
 * 创建时间: 2021/8/22$ 10:46 AM$
 * 联系方式: 419704299@qq.com
 * 修改人:   tangchao$
 * 修改时间: 2021/8/22$ 10:46 AM$
 * 修改备注:  [说明本次修改内容]
 */
public class RxLifecycle<T> implements LifecycleObserver, ObservableTransformer<T, T> {
    final CompositeDisposable compositeDisposable = new CompositeDisposable();

    @NonNull
    @Override
    public ObservableSource<T> apply(@NonNull Observable<T> upstream) {
        return upstream.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                compositeDisposable.add(disposable);
            }
        });

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy() {
        if (!compositeDisposable.isDisposed()) {
            Logger.d("RxLifecycle===onDestroy: ");
            compositeDisposable.dispose();
        }

    }

    public static <T> RxLifecycle bindRxLifecycle(LifecycleOwner lifecycleOwner) {
        RxLifecycle<T> lifecycle = new RxLifecycle<>();
        lifecycleOwner.getLifecycle().addObserver(lifecycle);
        return lifecycle;
    }
}
